package com.yxp423.ssmempl.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxp423.ssmempl.bean.SysLog;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.mapper.SysLogMapper;
import com.yxp423.ssmempl.service.ISysLogService;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-05-07 21:51
 * @Version: 1.0
 */
@Service
public class SysLogServiceImpl implements ISysLogService {

	Cache<String, IPage> sysLogCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);


	@Autowired
	private SysLogMapper sysLogMapper;

	@Override
	public int saveLog(SysLog sysLog) {


		return sysLogMapper.insert(sysLog);
	}

	@Override
	public AjaxResult getSysLogs(Page page) {

		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();
		if (ObjectUtil.isNull(user)) {

			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}



		QueryWrapper<SysLog> wrapper = new QueryWrapper<>();

		IPage iPage = sysLogCache.get("sysLogPage" + page.getCurrent());
		if (ObjectUtil.isNull(iPage)) {

			sysLogMapper.selectPage(page, wrapper.orderByDesc("log_time"));

			result.setSuccess(true);
			result.setData(page);
			sysLogCache.put("sysLogPage" + page.getCurrent(), page);

		}else {

			result.setSuccess(true);
			result.setData(iPage);

		}


//		if (page.getRecords().isEmpty()) {
//
//			result.setMsg("无记录");
//			result.setSuccess(false);
//			return result;
//
//		}



		return result;
	}
}
